#include "main.h"

static u32  fac_us=80;       /*80000000/1000000*/
                            /*us延时倍乘数*/
static u32 fac_ms=80000;    /*80000000/1000*/
                            /*ms延时倍乘数*/

volatile uint32_t systick_s = 0;    /*秒计数*/
volatile  uint8_t is_init = 1;    //ARM_CM4F port.c已初始化

void systick_init(void)
{
    is_init = 1;
#if 0
    S32_SysTick->CSR = S32_SysTick_CSR_ENABLE(0);
    S32_SysTick->RVR = SYSTICK_EXT_CLOCK_500MS_CNT; //重装载寄存器
    S32_SysTick->CVR = 0ul; //当前计数
    S32_SysTick->CSR = 0u; //控制寄存器
    //S32_SysTick_CSR_TICKINT此位设为1一定要建立中断服务函数
    S32_SysTick->CSR |= S32_SysTick_CSR_TICKINT(1)|S32_SysTick_CSR_ENABLE(1)| S32_SysTick_CSR_CLKSOURCE(1u);
#endif
}

void systick_deinit(void)
{

}

void delay_us(uint32_t us)
{
#if 0
    if (!is_init) systick_init();

    uint32_t end_count = 0, current = 0;

    current = get_systick_us();
    end_count = current + us;

    if (end_count == current) {
        return;
    } else if (end_count > current) {
        while (get_systick_us() < end_count);
    } else {
        while (get_systick_us() >= current);
        while (get_systick_us() < end_count);
    }
#else
    uint32_t current=S32_SysTick->CVR;
    while(S32_SysTick->CVR - current < us*fac_us);
#endif
}

void delay_ms(uint32_t ms)
{
#if 0
  if(!is_init) systick_init();

  uint32_t end_count = 0, current = 0;

  current = get_systick_ms();
  end_count = current + ms;

  if (end_count == current) {
    return;
  } else if (end_count > current) {
    while (get_systick_ms() < end_count);
  } else {
    while (get_systick_ms() >= current);
    while (get_systick_ms() < end_count);
  }
#else
    uint32_t current=S32_SysTick->CVR;
    while(S32_SysTick->CVR - current < ms*fac_ms);
#endif
}

/*
 * Max 4294967295(us)=4294967(us)=4294(s)=71(min)
 */
uint32_t get_systick_us(void)
{
    return xTaskGetTickCount()*1000;
}

uint32_t get_systick_ms(void)
{
  return xTaskGetTickCount();
}


void systick_test(void)
{
    static uint32_t tick=0;

    if(tick==0)
        tick=get_systick_ms();
    if(get_systick_ms()-tick > 1000){
        systick_s++;
        tick=0;
    }
}

